package com.haredot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haredot.entity.Comments;
import com.haredot.holder.TokenContextHolder;
import com.haredot.mapper.CommentsMapper;
import com.haredot.mapper.ResourceMapper;
import com.haredot.service.CommentsService;
import com.haredot.vo.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author Administrator
 * @description 针对表【tb_comments】的数据库操作Service实现
 * @createDate 2023-09-05 21:09:53
 */
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements CommentsService {

    @Resource
    private ResourceMapper resourceMapper;

    @Override
    public R<?> saveComments(Comments comments) {
        // 判断 该资源是否 是当前用户上传的（自己不允许评论自己的资源）
        Long currentUserId = TokenContextHolder.getCurrentUserId();
        comments.setUserId(currentUserId);
        comments.setState(0); // 设置评论状态
        // 查询 当前资源 的上传者 是否是当前用户
        com.haredot.entity.Resource resource = resourceMapper.selectById(comments.getResId());

        if (resource == null) return R.fail("资源不存在").build();

        if (Objects.equals(currentUserId, resource.getUserId())) {
            return R.fail("您不允许评论自己上传的资源").build();
        }
        // 判断 该资源是否被当前用户下载过
        long count = this.getBaseMapper().findDownloadHistoryByCurrentUserCount(currentUserId, comments.getResId());
        if (count == 0) {
            return R.fail("您无法评论没有下载过的资源").build();
        }
        // 如果该资源下载过、判断该资源是否已经被评论、如果被评论过，则不再允许评论~
        Long aLong = this.getBaseMapper().selectCount(new LambdaQueryWrapper<Comments>()
                .eq(Comments::getResId, comments.getResId())
                .eq(Comments::getUserId, currentUserId));

        if (aLong != null && aLong > 0) {
            return R.fail("您已评论过该资源、请勿重复评论").build();
        }
        // 评论该资源
        this.getBaseMapper().insert(comments);
        // 评论审核通过在发送 通知
        return R.ok().build();
    }
}




